package org.qydjk.console.service.impl;

import org.apache.commons.lang.StringUtils;
import org.qydjk.common.dao.IBaseDao;
import org.qydjk.common.pojo.SRoleResource;
import org.qydjk.common.pojo.SUser;
import org.qydjk.common.pojo.SUserRole;
import org.qydjk.console.service.ISysService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import java.util.List;

@Service
public class SysService implements ISysService{
    @Autowired
    private IBaseDao baseDao;

    public void updateRoleResource(Integer roleId, String resourceIds) throws Exception {
        // 先删除后添加,有点爆力
        SRoleResource roleResource = new SRoleResource();
        roleResource.setRoleId(roleId);
        List<SRoleResource> list = baseDao.findByExample(roleResource);
        if(list != null && list.size() > 0){
            baseDao.deleteAll(list);
        }

        // 如果资源id为空，判断为清空角色资源
        if (StringUtils.isBlank(resourceIds)) {
            return;
        }

        String[] resourceIdArray = resourceIds.split(",");
        for (String resourceId : resourceIdArray) {
            roleResource = new SRoleResource();
            roleResource.setRoleId(roleId);
            roleResource.setResourceId(Integer.parseInt(resourceId));
            baseDao.save(roleResource);
        }
    }

    public void addUser(SUser userVo, String roleIds) throws Exception {
        baseDao.save(userVo);
        String[] roles = roleIds.split(",");
        for (String string : roles) {
            SUserRole userRole = new SUserRole();
            userRole.setUserId(userVo.getId());
            userRole.setRoleId(Integer.valueOf(string));
            baseDao.save(userRole);
        }
    }

    public void updateUser(SUser user, String roleIds) throws Exception {
        baseDao.update(user);

        Integer id = user.getId();
        List<SUserRole> userRoles = baseDao.findByHql("from SUserRole sur where sur.userId = ?",id);
        if (userRoles != null && !userRoles.isEmpty()) {
            for (SUserRole userRole : userRoles) {
                baseDao.delete(userRole);
            }
        }

        String[] roles = roleIds.split(",");
        for (String string : roles) {
            SUserRole userRole = new SUserRole();
            userRole.setUserId(id);
            userRole.setRoleId(Integer.valueOf(string));
            baseDao.save(userRole);
        }
    }
}
